#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<stdbool.h>
#define NUM 128 
#define CMD_NUM 64 
int main()
{
    char command[NUM];
    char* argv[CMD_NUM] = {NULL};
    memset(command,0,sizeof(command));
    bool quit = false;
    while(!quit)
    {
        //1.用户提示符
        printf("[who@host dir]# ");
        fflush(stdout);//刷新缓冲区
        //2.获取命令行
        ssize_t n = read(0,command,NUM-1); //ls -l\n
        command[n-1] = '\0';
        //3.解析命令行
        char* seq = " ";
        argv[0] = strtok(command,seq);
        int index = 1;
        while(argv[index++] = strtok(NULL,seq)) ;
        
        //判断是否是执行内建命令
        if(strcmp("cd",argv[0]) == 0)
        {
            if(argv[1] != NULL)
                chdir(argv[1]);
            continue;
        }
        //4.创建子进程
        pid_t id = fork();
        if(id == 0) //child
        {
            //5.进程替换
            execvp(argv[0],argv);
        }
        //6.等待子进程返回
        int status = 0;
        waitpid(id,&status,0);
        printf("exit code:%d signal:%d\n",(status<<8)&0xff,status&0x7f);
    }
    return 0;
}